@echo off

md D:\data\var\solar-verse-iu-analysis\temp\
md C:\data\var\solar-verse-iu-analysis\temp\

setlocal

rem 修改当前页面的编码格式为utf8，注意只有当前页面，这是临时的(其他编码有需要的话自己查)
chcp 65001
rem chcp 936

for /f "usebackq delims=" %%i in (`powershell -Command "(Get-Date).ToString('yyyyMMddHHmm')"`) do set dtstr=%%i
set BAT_LOG="bat_%dtstr%.log"

set repull=%1
set repackage=%2
set recover=%3

if "%repull%" == "" set repull=false
if "%repackage%" == "" set repackage=true
if "%recover%" == "" set recover=true

set timestampstr=%TIME%
set timestampstr=%timestampstr::=.%


echo [%timestampstr%]repull=%repull%,repackage=%repackage%,recover=%recover% >> %BAT_LOG%

for /f "usebackq delims=" %%i in (`powershell -Command "(Get-Date).ToString('yyyy-MM-dd HH:mm:ss')"`) do set begin_time=%%i



set /a killNum=1
set /a killCnt=5

set app_port=8080
set base_dir=D:\data\apps\solar-verse-iu-analysis\
set project_name=solar-iu-analysis
set project_dir=%base_dir%%project_name%
set app_name=%project_name%
set app_dir=%base_dir%\%app_name%
set app_jar=%app_name%-1.0.0.jar
set app_jar_dir=%app_dir%\target
set app_jar_path=%app_jar_dir%\%app_jar%
set deploy_app_dir=D:\data\apps\solar-verse-iu-analysis\
set backup_app_dir=D:\data\apps\solar-verse-iu-analysis\backup\
set deploy_app_jar=%deploy_app_dir%%app_jar%
set console_log_name=solar-verse-iu-analysis.log
set console_log_path=%deploy_app_dir%%console_log_name%

echo BASE_DIR         = %base_dir%
echo PROJECT_NAME     = %project_name%
echo PROJECT_DIR      = %project_dir%
echo APP_NAME         = %app_name%
echo APP_DIR          = %app_dir%
echo APP_JAR          = %app_jar%
echo APP_JAR_DIR      = %app_jar_dir%
echo APP_JAR_PATH     = %app_jar_path%
echo DEPLOY_APP_DIR   = %deploy_app_dir%
echo BACKUP_APP_DIR   = %backup_app_dir%
echo DEPLOY_APP_JAR   = %deploy_app_jar%
echo CONSOLE_LOG_NAME = %console_log_name%
echo CONSOLE_LOG_PATH = %console_log_path%

set "jdk_opts=%jdk_opts% -Xms1024m -Xmx2048m"
set "jdk_opts=%jdk_opts% -XX:MetaspaceSize=1024M"
set "jdk_opts=%jdk_opts% -XX:MaxMetaspaceSize=1024M"
set "jdk_opts=%jdk_opts% -XX:+HeapDumpOnOutOfMemoryError"
set "jdk_opts=%jdk_opts% -XX:ErrorFile=%deploy_app_dir%\hs_err_pid%p.log"
set "jdk_opts=%jdk_opts% -Xlog:gc*:%deploy_app_dir%/gc.log:time"
set "jdk_opts=%jdk_opts% -XX:HeapDumpPath=%deploy_app_dir%"
set "jdk_opts=%jdk_opts% -XX:+PrintGCDetails"
set "jdk_opts=%jdk_opts% -Dspring.config.location=D:/data/apps/solar-iu-analysis/config/"
set "jdk_opts=%jdk_opts% -Dserver.port=%app_port%"
set "jdk_opts=%jdk_opts% -Doauth.authority.enabled=true"
set "jdk_opts=%jdk_opts% -Dudp.port=18084"
set "jdk_opts=%jdk_opts% -Dplatform.introduce.video-url=http://localhost:48888/swsc/video/swsc_flygo_introduce.mp4"
set "jdk_opts=%jdk_opts% -Dplatform.default.super-user-no=0"
set "jdk_opts=%jdk_opts% -Dplatform.uas.wayline.tenantNo=1007"
set "jdk_opts=%jdk_opts% -Dplatform.uas.wayline.organNo=100702002"
set "jdk_opts=%jdk_opts% -Dplatform.uas.wayline.save.interval=30"
set "jdk_opts=%jdk_opts% -Dschedule.task.drone-live.check-url=http://localhost:31985/api/v1/streams/"
set "jdk_opts=%jdk_opts% -Dschedule.task.forward-data.enable=false"
set "jdk_opts=%jdk_opts% -Dschedule.task.forward-data.scada.enable=false"
set "jdk_opts=%jdk_opts% -Dschedule.task.forward-data.bigdatap.enable=false"
set "jdk_opts=%jdk_opts% -Dschedule.task.patrol-task-auto.enable=true"
set "jdk_opts=%jdk_opts% -Danalysis.str.data=true"
rem set "jdk_opts=%jdk_opts% -Danalysis.str.le-diagnose.devices=101000102001,101000102004,103000102001,103000102002,103000102003,103000102004,103000102005,103000102006,103000102007"
set "jdk_opts=%jdk_opts% -Danalysis.str.le-diagnose.devices="

echo JDK_OPTS = %jdk_opts% >> %BAT_LOG%

set "JAVA_HOME=D:\data\apps\Java\jdk-11.0.16.1"
set "JRE_HOME=%JAVA_HOME%\jre"
set "CLASSPATH=.;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\jre\lib\tools.jar;%JRE_HOME%\lib;%CLASSPATH%"
set "PATH=%JAVA_HOME%\bin;%PATH%"

set "M2_HOME=D:\data\apps\Maven\apache-maven-3.8.8"
set "PATH=%M2_HOME%\bin;%PATH%"

rem set "GIT_HOME=C:\envs\Git"
rem set "PATH=%GIT_HOME%\bin;%PATH%"


java -version

call mvn --version

git --version

echo "判断目录是否存在..." >> %BAT_LOG%

IF NOT EXIST "%base_dir%" (
     mkdir "%base_dir%"
) ELSE (
     echo "[%base_dir%]文件夹已经存在" >> %BAT_LOG%
)

rem 拉取代码
:pullSource
echo "拉取代码开始..." >> %BAT_LOG%
cd /d %base_dir%
echo %cd%
REM checkAndMkdir %app_name%
IF NOT EXIST %project_name% (
    git clone -b master https://gitee.com/shuweisichuang/solar-iu-analysis.git
) ELSE (
    IF "%repull%"=="true" (
        echo "[%project_name%]已经存在, git pull更新" >> %BAT_LOG%
        cd /d %project_name%
        echo %cd%
        git pull
    ) ELSE (
        echo "无需更新代码" >> %BAT_LOG%
    )
)
echo "拉取代码结束..." >> %BAT_LOG%

rem 编译代码
:packageJar
echo "编译代码开始..." >> %BAT_LOG%
java -version
cd /d %project_dir%
echo %cd%
echo %app_dir%
echo %app_jar_dir%
git branch

if not exist %app_dir% (
	echo "首次编译..." >> %BAT_LOG%
    chcp 936
    call mvn clean -U
    rem -DskipTests,不执行测试用例,但编译测试用例类生成相应的class文件至target/test-classes下
    rem -Dmaven.test.skip=true,不执行测试用例,也不编译测试用例类
    rem mvn package -DskipTests
    call mvn package -Dmaven.test.skip=true
) else (
   if not exist %app_jar_dir% (
       echo "jar包目录不存在, 重新编译..." >> %BAT_LOG%
       dir
       chcp 936
       call mvn clean -U
       call mvn package -Dmaven.test.skip=true
   ) else (
       if exist %app_jar_path% (
           if "%repackage%" == "true" (
           	   echo "强制重新编译..." >> %BAT_LOG%
               chcp 936
               call mvn clean -U
               call mvn package -Dmaven.test.skip=true
           ) else (
               echo "无需重新打包" >> %BAT_LOG%
           )
       ) else (
       	   echo "jar包不存在, 重新编译..." >> %BAT_LOG%
           chcp 936
           call mvn clean -U
           call mvn package -Dmaven.test.skip=true
       )
   )
)
chcp 65001
cd /d %app_jar_dir%
dir /b
rem dir /b %app_jar_dir%
echo "编译代码结束..." >> %BAT_LOG%

set now_time_str=%time:~0,2%%time:~3,2%%time:~6,2%
set now_date_str=%date:~0,4%%date:~5,2%%date:~8,2%
set now=%date:~0,4%%date:~5,2%%date:~8,2%%time:~0,2%%time:~3,2%%time:~6,2%
set now=%now_time_str%
echo NOW=%now%
rem 复制jar
:copyAppJar
echo 复制Jar包开始... >> %BAT_LOG%
echo deploy_app_jar=%deploy_app_jar% >> %BAT_LOG%
IF EXIST %deploy_app_jar% (
    IF "%recover%"=="true" (
    	 rem %date:~0,4%%date:~5,2%%date:~8,2%

        REM del /F %deploy_app_jar%
        move %deploy_app_jar% %backup_app_dir%%app_jar%.%now%
        
        copy %app_jar_path% %deploy_app_jar%
    ) ELSE (
        echo %deploy_app_jar% 已存在, 且无需覆盖 >> %BAT_LOG%
    )
) ELSE (
	
	cd /d %app_jar_dir%
	dir /b
	echo app_jar_path=%app_jar_path%
	echo deploy_app_dir=%deploy_app_dir%
	echo app_jar=%app_jar%
    copy %app_jar_path% %deploy_app_jar% 
)
rem dir %deploy_app_dir%
cd %deploy_app_dir%
dir /b

echo 复制Jar包结束... >> %BAT_LOG%


netstat -ano | findstr ":%app_port%" > nul
if %errorlevel% neq 0 (
    echo %app_jar%端口%app_port%程序未运行 >> %BAT_LOG%
    goto startJar
) else (
    echo %app_jar%端口%app_port%程序正在运行 >> %BAT_LOG%
    goto stopAppJar
)
rem 停止服务
:stopAppJar
echo 服务开始停止... >> %BAT_LOG%
cd /d %deploy_app_dir%
dir /b
setlocal enabledelayedexpansion
rem 'netstat -ano ^| findstr /r ":[0-9]*[ ]*LISTENING" ^| findstr ":%app_port%"'
netstat -ano | findstr ":%app_port%" >> %BAT_LOG%
netstat -ano | findstr /r ":[0-9]*[ ]*LISTENING" | findstr ":%app_port%" >> %BAT_LOG%

for /f "tokens=5" %%a in ('netstat -ano ^| findstr /r ":[0-9]*[ ]*LISTENING" ^| findstr ":%app_port%"') do (
    echo  %%a >> %BAT_LOG%
    set PID=%%a
    echo %app_jar%端口%app_port%,对应进程ID: !PID! >> %BAT_LOG%
    rem taskkill /F /PID !PID!
)

if defined PID (
    echo "%app_jar%端口%app_port%,对应进程ID: !PID!" >> %BAT_LOG%
    if "%PID%" == "No" goto ENDLOOP
    taskkill /F /PID %PID%
    if %errorlevel% equ 0 (
        
        echo kill成功 >> %BAT_LOG%
    ) else (
        echo kill失败 >> %BAT_LOG%
    )
    echo -------------------------------------- >> %BAT_LOG%
    netstat -ano | findstr /r ":[0-9]*[ ]*LISTENING" | findstr ":%app_port%" >> %BAT_LOG%
    echo -------------------------------------- >> %BAT_LOG%
    set /a killNum=1
    set /a killCnt=5
    :LOOP
    SET PID=

    for /f "tokens=5" %%a in ('netstat -ano ^| findstr /r ":[0-9]*[ ]*LISTENING" ^| findstr ":%app_port%"') do set PID=%%a

    echo %PID% >> %BAT_LOG%
    if not defined PID goto ENDLOOP
    if %killNum% gtr %killCnt% (
        echo 强制 kill... >> %BAT_LOG%
        taskkill /F /PID %PID%
    )
    echo -e "[%app_jar%:%PID%]:[%killNum%],sleep 5, waiting..."
    setlocal enabledelayedexpansion
    for /f "tokens=5" %%a in ('netstat -ano ^| findstr /r ":[0-9]*[ ]*LISTENING" ^| findstr ":%app_port%"') do (
        set PID=%%a
        echo "%app_jar%端口%app_port%,对应进程ID: %PID%"
    )
    endlocal
    set /a killNum+=1
    timeout /t 5 >nul
    goto LOOP

)
echo "========================" >> %BAT_LOG%
rem if "%PID%"=="" (
rem     echo "服务未运行"
rem )
rem if defined PID (
rem     if "%PID%" == "No" goto ENDLOOP
rem     taskkill /F /PID %PID%
rem     set /a killNum=1
rem     set /a killCnt=5
rem     :LOOP
rem     if not defined PID goto ENDLOOP
rem     if !killNum! gtr !killCnt! (
rem         echo 强制 kill...
rem         taskkill /F /PID %PID%
rem     )
rem     echo -e "[%app_jar%:%PID%]:[%killNum%],sleep 5, waiting..."
rem     setlocal enabledelayedexpansion
rem     for /f "tokens=2" %%a in ('tasklist /FI "imagename eq %app_jar%" /NH') do (
rem         set PID=%%a
rem     )
rem     endlocal
rem     set /a killNum+=1
rem     timeout /t 5 >nul
rem     goto LOOP
rem )
:ENDLOOP
echo kill success >> %BAT_LOG%
echo 服务停止完成... >> %BAT_LOG%
rem goto :eof

echo 暂停... >> %BAT_LOG%
timeout /t 5 > nul
ping -n 5 127.0.0.1 > nul
echo 继续... >> %BAT_LOG%

rem 启动服务
:startJar
echo 服务开始启动... >> %BAT_LOG%
cd /d %deploy_app_dir%
echo. > %console_log_path%
set BUILD_ID=dontKillMe && start "SOLAR-VERSE-IU-ANALYSIS" %JAVA_HOME%\bin\java -Dfile.encoding=UTF-8 %jdk_opts% -jar %deploy_app_jar% >> %console_log_path% 2>>&1
echo "----------"
REM ping 127.0.0.1 -n 6 > NUL
REM timeout /t 5 >nul
timeout /nobreak /t 10
echo 服务启动完成... >> %BAT_LOG%

rem 显示日志
@echo off
setlocal
echo tailing %console_log_path% ...
set "keyword=started on port"
echo %keyword% >> %BAT_LOG%
for /F "usebackq delims=" %%i in (`type "%console_log_path%" ^| findstr /C:"%keyword%" /C:" "`) do (
  echo %%i
  set "line=%%i"
  setlocal enabledelayedexpansion
  if "!line:%keyword%=!" neq "!line!" (
    echo.
    echo ******** %deploy_app_jar% start completed********** >> %BAT_LOG%
    echo.
    for /f "tokens=2" %%a in ('tasklist /FI "IMAGENAME eq cmd.exe" /FI "WINDOWTITLE eq %~nx0*" /NH /FO CSV') do set "pid=%%~a"
    taskkill /F /T /PID %pid%
  )
  endlocal
)


@echo off
setlocal
for /f "usebackq tokens=1,2 delims==" %%a in ('wmic os get LocalDateTime /value') do if '.%%a'=='.LocalDateTime' set "end_time=%%b"
set "end_time=%end_time:~0,4%-%end_time:~4,2%-%end_time:~6,2% %end_time:~8,2%:%end_time:~10,2%:%end_time:~12,2%"
set "begin_time=%date% %time%"
echo "启动开始时间: %begin_time%, 结束时间: %end_time%" >> %BAT_LOG%
for /f "delims=" %%a in ('powershell -Command "[DateTime]$begin_time=[DateTime]\"%begin_time%\"; [DateTime]$end_time=[DateTime]\"%end_time%\"; $total_time=$end_time-$begin_time; Write-Output $total_time.ToString(\"dd\.hh\:mm\:ss\")"') do set "total_time=%%a"
echo "总时长： %total_time%" >> %BAT_LOG%




rem set jdk_opts=%jdk_opts% -Xms512m -Xmx800m
rem set jdk_opts=%jdk_opts% -XX:MetaspaceSize=256M
rem set jdk_opts=%jdk_opts% -XX:MaxMetaspaceSize=256M
rem set jdk_opts=%jdk_opts% -XX:+HeapDumpOnOutOfMemoryError
rem set jdk_opts=%jdk_opts% -XX:ErrorFile=%deploy_app_dir%/hs_err_pid%%p.log
rem set jdk_opts=%jdk_opts% -Xlog:gc*:%deploy_app_dir%/gc.log:time
rem set jdk_opts=%jdk_opts% -XX:HeapDumpPath=%deploy_app_dir%
rem set jdk_opts=%jdk_opts% -XX:+PrintGCDetails
rem set jdk_opts=%jdk_opts% -Dspring.config.location=/data/apps/solar-verse/config/
rem set jdk_opts=%jdk_opts% -Dspring.profiles.active=ssjn,dji
rem set jdk_opts=%jdk_opts% -Dserver.port=8085
rem set jdk_opts=%jdk_opts% -Doauth.authority.enabled=true
rem set jdk_opts=%jdk_opts% -Dudp.port=18083
rem set jdk_opts=%jdk_opts% -Dplatform.introduce.video-url=http://218.23.206.21:48888/swsc/video/swsc_flygo_introduce.mp4
rem set jdk_opts=%jdk_opts% -Dplatform.default.super-user-no=0
rem set jdk_opts=%jdk_opts% -Dplatform.uas

rem pause